package com.hornsun.authorization.service;

import com.hornsun.config.ConfigInfo;
import com.hornsun.config.IRedisService;
import com.hornsun.data.constant.types.LineStatus;
import com.hornsun.data.dbo.*;
import com.hornsun.data.repository.mapper.AuthInfoMapper;
import com.hornsun.data.repository.mapper.AuthorizationMapper;
import com.hornsun.util.SerializeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by 编译中... on 2018/7/9.
 */
@Service
public class AuthorizationService {

    @Autowired
    private AuthInfoMapper authInfoMapper;

    @Autowired
    private AuthorizationMapper authorizationMapper;

    @Autowired
    private IRedisService service;

    @Autowired
    private ConfigInfo configInfo;

    public static final Integer limit = 10;

    public List<AuthClient> getAuthClientDTO(int page){
        int offset = (page-1)*limit;
        List<AuthClient> authClientDTOList = authInfoMapper.getAuthClientList(offset,limit);
        for(AuthClient authClient : authClientDTOList ){
            if (authClient.getAccount()!=null){
                authClient.setLineStatus(getLineStatus(authClient.getAccount()));
            }else {
                authClient.setLineStatus(LineStatus.OFFLINE.getType());
            }

        }
        return authClientDTOList;
    }

    private int getLineStatus(String account){
        if (service.isKeyExists(configInfo.getRedisAccount(),account)){
            byte[] clientInfoBytes = (byte[]) service.get(configInfo.getRedisAccount(),account);
            ClientInfo clientInfo = (ClientInfo) SerializeUtils.deSerialize(clientInfoBytes);
            if (clientInfo!=null){
                List<OfflineInfo> offlineInfoList = clientInfo.getOfflineInfoList();
                if (offlineInfoList.size()!=0){
                    return LineStatus.OFFLINE_AUTH.getType();
                }
                List<AccountInfo> accountInfoList = clientInfo.getAccountInfoList();
                if (accountInfoList.size()!=0){
                    return LineStatus.ONLINE.getType();
                }

            }
        }
        return LineStatus.OFFLINE.getType();
    }

    public boolean hasAuth(String guid){
        AuthorizationExample authorizationExample = new AuthorizationExample();
        AuthorizationExample.Criteria criteria = authorizationExample.createCriteria();
        criteria.andClientGuidEqualTo(guid);
        return authorizationMapper.countByExample(authorizationExample) > 0;
    }



}
